/*
 * handle_write.c
 *
 *  Created on: 2009-5-5
 *      Author: tian
 */

#include"tcpipsim.h"

void handle_write(msg *pmsg){
	sockmsg retmsg;
	memset(&retmsg,0,sizeof(sockmsg));
	int i=0;
	struct tcpcb *ptcpcb=get_tcpcb_by_sock(pmsg->pid,pmsg->sock);
	if(ptcpcb==NULL){
		retmsg.mtype=pmsg->sock;
		retmsg.ret=-1;
		if(msgsnd(pmsg->msgqid,&retmsg,sizeof(sockmsg)-sizeof(long),IPC_NOWAIT)<0){
			fprintf(stderr,"can not send message to application layer\n");
			return;
		}
	}
	else{
		for(i=0;i<pmsg->buflen;i++){
			ptcpcb->sndbuf[i]=pmsg->buf[i];
		}
		ptcpcb->sndlen=pmsg->buflen;
		if(tcp_input(NULL,NULL,ptcpcb,send_data)<0){
			retmsg.mtype=pmsg->sock;
			retmsg.ret=-1;
			if(msgsnd(ptcpcb->msgqid,&retmsg,sizeof(sockmsg)-sizeof(long),IPC_NOWAIT)<0){
				fprintf(stderr,"can not send message to application layer\n");
				return;
			}
		}
	}
}
